﻿#include"happ.h"
#include "uv.h"
#include "hnode.h"
struct s_app
{
    uv_loop_t app_loop;
    uv_timer_t app_guard_timer;
};
static const char* app_log_tag = "app_log";

static struct s_app* g_app = NULL;
static void app_timer_cb(uv_timer_t* handle) {
    // ASSERT(handle != NULL);
    // ASSERT(1 == uv_is_active((uv_handle_t*)handle));
}

void init_app(app_req_func app) {
    if (g_app) {
        hlog(app_log_tag, LOG_ERROR, 1, "app already inited \n");
        return;
    }
    g_app = malloc(sizeof(struct s_app));
    if (!g_app) {
        hlog(app_log_tag, LOG_ERROR, 1, "out of memory\n");
        return;
    }
    memset(g_app, 0, sizeof(struct s_app));
    uv_loop_init(&g_app->app_loop, app);
    uv_timer_init(&g_app->app_loop, &g_app->app_guard_timer);
    auto r = uv_timer_start(&g_app->app_guard_timer, app_timer_cb, 50, 1);/* GUARD_TIMEER_GAP_MS, MAX_UINT64);*/
}

void h_run_once() {
    if (!g_app) {
        hlog(app_log_tag, LOG_ERROR, 1, "app not inited \n");
        return;
    }
    auto r = uv_run(g_app, UV_RUN_ONCE);
}

void uninit_app() {
    if (!g_app) {
        hlog(app_log_tag, LOG_ERROR, 1, "app not inited \n");
        return;
    }
    uv_timer_stop(&g_app->app_guard_timer);
    uv_stop(&g_app->app_guard_timer);
    free(g_app);
    g_app = NULL;
}

int post_to_app(struct uv_app_s* s) {
    if (!g_app) {
        hlog(app_log_tag, LOG_ERROR, 1, "post_to_app app not inited \n");
        return 0;
    }

    s->loop = &g_app->app_loop;
    if (!PostQueuedCompletionStatus(g_app->app_loop.iocp,
                                    s->u.io.overlapped.InternalHigh,
                                    0,
                                    &s->u.io.overlapped)) {
        hlog(app_log_tag, LOG_ERROR, 1, "post_to_app error [%d] \n", GetLastError());
    }
    return 1;
}
